package com.hs.projectback.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hs.projectback.model.domain.User;
import com.hs.projectback.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 缓存预热
 *
 * @author 韩帅
 */
@Slf4j
@Component
public class PreCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private List<Long> mainUserList = Arrays.asList(1L);

    @Scheduled(cron = "0 31 0 * * *")
    public void doCacheRecommendUsers() {
        //Redisson 本质是一个Redis，getLock相当于存redis中的key
        RLock rLock = redissonClient.getLock("yupao:precachejob:docache:lock");
        try {
            //给redis加锁
            // 第一个参数 ：其他进程没抢到锁后再次尝试抢锁的时间间隔，0为不再次抢夺，直接放弃
            // 第二个参数 ：锁的过期时间，-1代表 Redisson会执行看门狗机制，防止进程任务没完成，锁被提前放弃。
            // 看门狗机制：每隔10秒自动把锁的过期时间调整为30秒
            if (rLock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                //设置主要缓存预热用户
                for (Long userId : mainUserList) {
                    //建立数据库连接
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    //获取数据库中20条用户的信息
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                    //建立spring-data-redis的的对象
                    //类型为 String : Object
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    String redisKey = String.format("yupao:user:recommend:%s", userId);
                    //写缓存
                    try {
                        valueOperations.set(redisKey, userPage, 30000, TimeUnit.MICROSECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
        } finally {
            //isHeldByCurrentThread()： 判断当前锁的id是否与当前进程的id相同
            //只能释放自己的锁
            if (rLock.isHeldByCurrentThread()) {
                //若当前进程id是给redis加锁的进程id，则释放锁
                rLock.unlock();
            }
        }
    }
}
